package com.easwift.qsp.das.xgy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.easwift.qsp.das.Test;
import com.easwift.qsp.util.BitUtils;
import com.easwift.qsp.util.DataSourceUtils;
import com.easwift.qsp.util.LogUtils;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @author: huameng
 * @date: 2020年07月29日 9:02
 */
public class XGYSocketReadThread extends Thread {
    private BufferedInputStream bis;
    private long socketThreadId;
    //设置一个标志位

    public XGYSocketReadThread(BufferedInputStream bis,long socketThreadId) {
        super();
        this.bis = bis;
        this.socketThreadId = socketThreadId;
    }

    @Override
    public void run() {
        boolean flag = true;
        while (flag) {
            if (!Test.socketThreadSet.contains(socketThreadId)) {
                flag = false;
            }
            try {
                if (bis.available() != 0) {

                    byte[] bytes = new byte[bis.available()];
                    int len = bis.read(bytes, 0, bis.available());
                    System.out.print("端口8090读取到数据：");
                    LogUtils.printFrame(bytes);

                    //应该对数据进行一下处理
                    if (bytes.length == 6) {
                        //设备地址
                        int address = Byte.toUnsignedInt(bytes[0]) + (Byte.toUnsignedInt(bytes[1]) << 8);

                        byte[] bbs = new byte[1];
                        System.arraycopy(bytes, 4, bbs, 0, 1);
                        bbs = BitUtils.reverseArray(bbs);//反转数组

                        String f = BitUtils.toHexString(bbs);

                        //存储到数据库
                        if (f.equals("ff") || f.equals("FF")) {
                            System.out.println("进行抓拍");

                            //方案一、萤石云进行抓拍

                            /*String imageUrl = capture();
                            if(imageUrl==null||imageUrl.equals("")) continue;
                            String sql = String.format("insert into tb_device_xgdata (address,value,imageurl,createtime) values (%s,%s,%s,%s)",String.valueOf(address),1,"'"+imageUrl+"'","now()");
                            DataSourceUtils.getJdbcTemplate().execute(sql);*/

                            //方案二、传感器触发抓拍
                           /* Thread.sleep(2000);
                            File f=new File("C:\\picfile");
                            traverseFile(f);*/

                            //方案二改进、报警信号触发 保存一个时间段的区间

                            String sql = String.format("insert into tb_device_xgdata (address,value,createtime) values (%s,%s,%s)", String.valueOf(address), 1, "now()");
                            DataSourceUtils.getJdbcTemplate().execute(sql);


                        }
                    }
                }
        } catch(Exception e){
            System.out.println(e);
        }
    }
    }

    //方案一：通过萤石云进行抓拍
    public String capture() {
        String token=null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String fileUrl = "";
        String fileName = "";
        try{
            //先去获取token，如果时间超过天重新获取
            String sql = "select * from tb_token where id =(SELECT max(id) FROM tb_token)";
            TokenInfo info= DataSourceUtils.getJdbcTemplate().queryForObject(sql, new Object[]{}, new  BeanPropertyRowMapper<TokenInfo>(TokenInfo.class));
            System.out.println("token信息"+info.getToken());
            //TokenInfo info=(TokenInfo) DataSourceUtils.getJdbcTemplate().queryForObject(sql,new TokenInfo());
            int days = (int) ((new Date().getTime() - info.getCreatetime().getTime()) / (1000*3600*24));
            token=info.getToken();
            if(days>6||info==null){
                // 超过6天就重新获取一次 获取访问萤石云接口的token
                String getTokenUrl = "https://open.ys7.com/api/lapp/token/get";
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("appKey", "fb60072e3ce0416d844d7f281da699fe");
                param.put("appSecret", "f5f5ddbeb440046c7e6bfd128443cb21");
                String result = HttpUtil.post(getTokenUrl, param);
                JSONObject jsonObject = JSONUtil.parseObj(result);
                token = JSONUtil.parseObj(jsonObject.get("data")).get("accessToken").toString();
                //并保存到数据库
                String sql1 = String.format("insert into tb_token (token,createtime) values (%s,%s)","'"+token+"'","now()");
                DataSourceUtils.getJdbcTemplate().execute(sql1);
            }

            // 抓拍图片
            String captureUrl = "https://open.ys7.com/api/lapp/device/capture";
            String deviceSerial = "C91418338";
            Integer channelNo = 1;
            Map<String, Object> param1 = new HashMap<String, Object>();
            param1.put("accessToken", token);
            param1.put("deviceSerial", deviceSerial);
            param1.put("channelNo", channelNo);
            //请求抓拍 时间慢
            String result1 = HttpUtil.post(captureUrl, param1);

            JSONObject jsonObject1 = JSONUtil.parseObj(result1);
            String msg= jsonObject1.get("msg").toString();
            System.out.println(msg);
            if(msg.equals("设备不在线")){
                return null;
            }
            String picUrl = JSONUtil.parseObj(jsonObject1.get("data")).get("picUrl").toString();

            // 下载并本地保存抓拍到的图片
            String path = picUrl;
            URL url = null;
            HttpURLConnection con = null;
            String rootFile = "c:\\file";


            String status = "";

            url = new URL(path);

            con = (HttpURLConnection) url.openConnection();
            inputStream = con.getInputStream();
            fileName = deviceSerial + "_" + System.currentTimeMillis();
            fileUrl = "c:/file/" + fileName + ".jpg";

            status = "0";
            File file = new File(rootFile);
            if (!file.exists()) {
                file.mkdir();
            }
            outputStream = new FileOutputStream(fileUrl);
            int n = -1;
            byte b[] = new byte[1024];
            while ((n = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, n);
            }
            outputStream.flush();

        }catch (Exception e){
            e.printStackTrace();
        }

        return "file/" + fileName + ".jpg";
    }

    //方案二：传感器触发抓拍
     public void traverseFile(File f){

        File[] files=f.listFiles();
        for (File fi:files){
            //如果是目录
            if (fi.isDirectory()){
                //System.out.println(fi);
                //递归
                traverseFile(fi);
            }
            else{
                //如果是文件
                // 不打印隐藏文件
                if (!fi.isHidden())
                {
                    String filename=fi.getName();
                    System.out.println("文件的绝对路径："+fi);
                    //判断一下，只有当文件名符合条件才可以执行
                    if(filename.length()>=46){
                        //分割字符串
                        String[] s = filename.split("_");
                        Date date = DateUtil.parse(s[2], "yyyyMMddHHmmssSSS");
                        System.out.println(date.toString());

                        //保存到数据库中
                        String sql = String.format("INSERT INTO tb_device_xgdata(address,value,imageurl,createtime)" +
                                "SELECT %s,1,%s,%s FROM dual" +
                                " WHERE NOT EXISTS(SELECT imageurl FROM tb_device_xgdata where imageurl=%s)","'"+s[1]+"'","'picfile/"+filename+"'","'"+date.toString()+"'","'picfile/"+filename+"'");
                        DataSourceUtils.getJdbcTemplate().execute(sql);
                    }

                }
            }

        }

    }
}
